package com.SouthernWall_404.Age_Capitalism.common.Network.S2C;

import com.SouthernWall_404.Age_Capitalism.common.Network.ClientHandler.MerchantClientHandler;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.protocol.game.ClientGamePacketListener;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.trading.MerchantOffer;
import net.minecraft.world.item.trading.MerchantOffers;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.fml.DistExecutor;
import net.minecraftforge.network.NetworkEvent;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

public class MerchantServerPacket {

    private final int containerId;
    private final MerchantOffers offers;
    private final int villagerLevel;
    private final int villagerXp;
    private final boolean showProgress;
    private final boolean canRestock;

    public MerchantServerPacket(int p_132456_, MerchantOffers p_132457_, int p_132458_, int p_132459_, boolean p_132460_, boolean p_132461_) {
        this.containerId = p_132456_;
        this.offers = p_132457_;
        this.villagerLevel = p_132458_;
        this.villagerXp = p_132459_;
        this.showProgress = p_132460_;
        this.canRestock = p_132461_;
    }

    public MerchantServerPacket(FriendlyByteBuf p_178985_) {
        this.containerId = p_178985_.readVarInt();
        this.offers = MerchantOffers.createFromStream(p_178985_);
        this.villagerLevel = p_178985_.readVarInt();
        this.villagerXp = p_178985_.readVarInt();
        this.showProgress = p_178985_.readBoolean();
        this.canRestock = p_178985_.readBoolean();
    }

    public void encode(FriendlyByteBuf p_132470_) {
        p_132470_.writeVarInt(this.containerId);
        this.offers.writeToStream(p_132470_);
        p_132470_.writeVarInt(this.villagerLevel);
        p_132470_.writeVarInt(this.villagerXp);
        p_132470_.writeBoolean(this.showProgress);
        p_132470_.writeBoolean(this.canRestock);
    }

    public void handle(Supplier<NetworkEvent.Context> ctx)
    {
        ctx.get().enqueueWork(() ->
                // 确保其仅在物理客户端上执行
                DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () ->MerchantClientHandler.handleOpenPacket(this,ctx))
        );
        ctx.get().setPacketHandled(true);
    }

    public int getContainerId() {
        return this.containerId;
    }

    public MerchantOffers getOffers() {
        return this.offers;
    }

    public int getVillagerLevel() {
        return this.villagerLevel;
    }

    public int getVillagerXp() {
        return this.villagerXp;
    }

    public boolean showProgress() {
        return this.showProgress;
    }

    public boolean canRestock() {
        return this.canRestock;
    }
}
